package com.sxyc.utils;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;

public class QMapUtils {

	// 使用jFinal 日志
	private static com.jfinal.log.Log log = com.jfinal.log.Log.getLog(QMapUtils.class);

	private static String key = "TPIBZ-W3M3O-I2AWU-SXVJ2-XLW56-73BI6";// PropKit.get("qqMap_key")

	private static String sKey = "53xDBjyK139VwKITxRpHJyaKkWrYdv";// PropKit.get("qqMap_sKey")

	private static String rootUrl = "http://apis.map.qq.com";

	public static SortedMap<String, String> _paramsMap = new TreeMap<String, String>();

	QMapUtils() {
		key = PropKit.get("qqMap_key");
		sKey = PropKit.get("qqMap_sKey");
	}

	private static String getSN(String url, SortedMap<String, String> paramsMap) {
		String sn = "";
		try {
			if (paramsMap == null) {
				paramsMap = _paramsMap;
			}
			// 如果参数中有key，则移除重新添加
			if (paramsMap.containsKey("key")) {
				paramsMap.remove("key");
			}
			paramsMap.put("key", key);
			String paramsStr = toQueryString(paramsMap);
			String basicString = url + "?" + paramsStr;
			return MD5(URLEncoder.encode((basicString + sKey), "UTF-8"));
		} catch (Exception e) {
			log.error("getSN Exception ：" + e.getMessage());
		}
		return sn;
	}

	/**
	 * 将Map参数转换为String参数
	 * 
	 * @param data
	 * @return
	 */
	private static String toQueryString(SortedMap<?, ?> paramsMap) {
		StringBuffer queryString = new StringBuffer();
		try {
			Set es = paramsMap.entrySet();// 所有参与传参的参数按照accsii排序（升序）
			Iterator it = es.iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				String k = (String) entry.getKey();
				Object v = entry.getValue();
				if (null != v && !"".equals(v)) {
					queryString.append(k + "=" + v + "&");
				}
			}
		} catch (Exception e) {
			log.error("toQueryString Exception ：" + e.getMessage());
		}
		return queryString.toString();
	}

	/**
	 * MD5加密
	 * 
	 * @param md5
	 * @return
	 */
	private static String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (Exception e) {
			log.error("MD5 Exception ：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 百度API请求方法
	 * 
	 * @param url
	 *            请求地址,如：/geocoder/v2/
	 * @param paramsMap
	 *            请求参数，忽略：ak、output（默认为：json）
	 * @return
	 */
	public static String getResult(String url, SortedMap<String, String> paramsMap) {
		String result = "";
		try {
			if (paramsMap == null) {
				paramsMap = _paramsMap;
			}
			// 如果参数中有ak，则移除重新添加
			if (paramsMap.containsKey("key")) {
				paramsMap.remove("key");
			}
			paramsMap.put("output", "json");
			String sn = getSN(url, paramsMap);
			String requestUrl = rootUrl + url + "?" + toQueryString(paramsMap) + "&sn=" + sn;
			result = HttpKit.get(requestUrl);
			log.info("url = " + url);
			log.info("paramsMap = " + toQueryString(paramsMap));
//			log.info("result = " + result);
		} catch (Exception e) {
			log.error("getResult Exception ：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 根据经纬度获取地址信息
	 * 
	 * @param lat
	 *            纬度
	 * @param lng
	 *            经度
	 * @return
	 */
	public static String getAddress(double lat, double lng) {
		String address = "";
		try {
			String url = "/ws/geocoder/v1/";
			// SortedMap<String, String> paramsMap = new TreeMap<String,String>();
			_paramsMap.clear();
			_paramsMap.put("location", lat + "," + lng);
			String result = getResult(url, _paramsMap);
			if (result != null) {
				JSONObject data = JSONObject.parseObject(result);
				String status = data.getString("status");
				if ("0".equals(status)) {
					JSONObject resultData = (JSONObject) data.get("result");
					if (resultData != null) {
						JSONObject recommendData = (JSONObject)resultData.get("formatted_addresses");
						String recommend = "";
						if(recommendData!=null){
							recommend = recommendData.getString("recommend");
						}
						//address = recommend;
						address = resultData.getString("address");
					}
				} else {
					String message = data.getString("message");
					log.error("getAddress 失败！错误代码：" + result + ";错误消息：" + message);
				}
			}
		} catch (Exception e) {
			log.error("getAddress Exception：" + e.getMessage());
		}
		return address;
	}

	public static void main(String[] args) {
		PropKit.use("appConfig.properties");
		QMapUtils map = new QMapUtils();
		System.out.println("key = " + map.key);
		System.out.println("sKey = " + map.sKey);
		
		//获取西安市钟楼（东西南北四条大街交汇处）地址
		String result = QMapUtils.getAddress(34.265678, 108.953382);
		System.out.println(result);
	}
}
